<template>
	<view class="step-item">
		<view class="step-header">
			<view class="step-icon">📝</view>
			<view class="step-title-main">活动信息填写</view>
			<view class="step-description">请填写活动的基本信息，包括名称、类型、时间、地点等</view>
		</view>

		<view class="form-container">
			<view class="form-item">
				<view class="label">活动名称</view>
				<u-input v-model="formData.name" placeholder="请输入活动名称" @input="clearError('name')" @change="saveToCache" />
				<view v-if="errors.name" class="error-text">{{ errors.name }}</view>
			</view>

			<view class="form-item">
				<view class="label">活动类型</view>
				<view class="cell-wrapper">
					<u-cell-group :border="false">
						<u-cell-item :title="activityType || '请选择活动类型'" :arrow="true" arrow-direction="right"
							@click="showActionSheet"></u-cell-item>
					</u-cell-group>
				</view>
				<view v-if="errors.type" class="error-text">{{ errors.type }}</view>
			</view>

			<view class="form-item">
				<view class="label">适用年龄</view>
				<view class="age-range">
					<u-input v-model="formData.min_age" type="number" placeholder="最小年龄" :border="true" :clearable="true" @input="clearError('age')" />
					<text class="separator">-</text>
					<u-input v-model="formData.max_age" type="number" placeholder="最大年龄" :border="true" :clearable="true" @input="clearError('age')" />
				</view>
				<view v-if="errors.age" class="error-text">{{ errors.age }}</view>
			</view>

			<view class="form-item">
				<view class="label">报名人数限制</view>
				<view class="number-range">
					<u-input v-model="formData.min_participants" type="number" placeholder="最小人数" :border="true"
						:clearable="true" @input="clearError('participants')" />
					<text class="separator">-</text>
					<u-input v-model="formData.max_participants" type="number" placeholder="最大人数" :border="true"
						:clearable="true" @input="clearError('participants')" />
				</view>
				<view v-if="errors.participants" class="error-text">{{ errors.participants }}</view>
			</view>

			<view class="form-item">
				<view class="label">活动开始时间</view>
				<view class="input-with-icon" @tap="chooseStartTime">
					<view class="inputview" :style="{ color: formData.start_time_text ? '#000000' : 'rgb(192, 196, 204)' }">
						{{formData.start_time_text || "请选择开始时间"}}
					</view>
					<u-icon class="suffix-icon" name="calendar" size="24"></u-icon>
				</view>
				<view v-if="errors.start_time" class="error-text">{{ errors.start_time }}</view>
			</view>

			<view class="form-item">
				<view class="label">活动截止时间</view>
				<view class="input-with-icon" @click="showEndTimePicker=true">
					<view class="inputview" :style="{ color: formData.end_time_text ? '#000000' : 'rgb(192, 196, 204)' }">
						{{formData.end_time_text || "请选择结束时间"}}
					</view>
					<u-icon class="suffix-icon" name="calendar" size="24"></u-icon>
				</view>
				<view v-if="errors.end_time" class="error-text">{{ errors.end_time }}</view>
			</view>

			<view class="form-item">
				<view class="label">活动地点</view>
				<view class="input-with-icon" @click="toChooseMap">
					<view class="inputview" :style="{ color: formData.address ? '#000000' : 'rgb(192, 196, 204)' }">
						<view style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;margin-right: 40rpx;">
							{{formData.address || "请选择地址"}}
						</view>
						<u-icon class="suffix-icon" style="color:#0dc160" name="map-fill" size="24"></u-icon>
					</view>
				</view>
				<view v-if="errors.address" class="error-text">{{ errors.address }}</view>
			</view>

			<view class="form-item">
				<view class="label">活动简介</view>
				<view class="description-wrapper">
					<u-input type="textarea" v-model="formData.description" placeholder="请输入活动简介" @input="clearError('description')" />
				</view>
				<view v-if="errors.description" class="error-text">{{ errors.description }}</view>
			</view>

			<view class="form-item">
				<view class="label">活动封面图片</view>
				<u-upload 
					:action="uploadUrl" 
					width="190" 
					height="190" 
					:header="uploadHeaders"
					:file-list="displayFileList"
					@on-success="afterRead" 
					@on-remove="deletePic" 
					@on-choose="onChooseFile"
					:max-count="1" 
					:multiple="false"
					:deletable="true"
					:previewFullImage="true"
					accept="image/*"
					:auto-upload="true" 
					:show-progress="false" />
				<view v-if="errors.images" class="error-text">{{ errors.images }}</view>
			</view>

			<view class="bottom-buttons">
				<view class="next-btn" @click="save">
					<text>下一步</text>
				</view>
			</view>
		</view>
		
		<!-- #ifdef H5 -->
		<u-popup mode="right" width="100%" height="100%" v-model="showMap" @open="openMap">
			<map-selector ref="mapSelector" @select="handlerSelectMap" @cancel="showMap = false" />
		</u-popup>
		<!-- #endif -->

		<u-picker v-model="showStartTimePicker" mode="time" @confirm="handleStartTimeConfirm"></u-picker>
		<u-picker v-model="showEndTimePicker" mode="time" @confirm="handleEndTimeConfirm"></u-picker>
		<u-action-sheet :list="actionSheetList" v-model="showSheet" @click="selectType"
			:safe-area-inset-bottom="true"></u-action-sheet>
	</view>
</template>

<script>
	import {
		addActivity,
		editActivity,
		trainerList
	} from '@/api/launchevent.js';
	import {
		baseURL
	} from '@/config/app.js'
	import store from 'store';
	import mapSelector from '@/components/map/index.vue';
	import {
		urlencode
	} from '@/utils/tools';
	// 日期格式化函数
	function formatDate({
		year,
		month,
		day,
		timestamp
	}) {
		const date = new Date(timestamp * 1000);
		const hours = date.getHours().toString().padStart(2, '0');
		const minutes = date.getMinutes().toString().padStart(2, '0');
		const seconds = date.getSeconds().toString().padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
	// 在组件顶部添加防抖函数
	function debounce(fn, delay) {
		let timer = null;
		return function (...args) {
			if (timer) clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(this, args);
			}, delay);
		};
	}
	export default {
		components: {
			mapSelector,
		},
		props: {
			activityId: {
				type: [Number, String],
				default: null
			},
			activityData: {
				type: Object,
				default: () => ({})
			},
			formCache: {
				type: Object,
				default: () => ({})
			}
		},
		computed: {
			activityType() {
				return this.actionSheetList.find(item => item.value === this.formData.type)?.text || '';
			},
			imageUrls() {
				return this.uploadedImages.map(file => file.url);
			},
			// 智能决定是否使用file-list绑定
			shouldUseFileList() {
				// 如果正在上传，不使用file-list（避免重复渲染）
				if (this.isUploading) {
					console.log('shouldUseFileList: false - 正在上传');
					return false;
				}
				
				// 如果用户已经交互过（上传或删除），不使用file-list，让组件自主管理
				if (this.hasUserInteracted) {
					console.log('shouldUseFileList: false - 用户已交互');
					return false;
				}
				
				// 如果有缓存的图片数据且用户未交互，使用file-list显示
				const hasCachedImages = this.uploadedImages.length > 0;
				console.log('shouldUseFileList:', hasCachedImages, '- uploadedImages长度:', this.uploadedImages.length, '- hasUserInteracted:', this.hasUserInteracted);
				return hasCachedImages;
			},
			// 为u-upload组件准备的file-list数据
			displayFileList() {
				if (!this.shouldUseFileList) {
					console.log('displayFileList: [] - 不使用file-list');
					return [];
				}
				const result = this.uploadedImages.map(file => ({
					url: file.url,
					name: file.name || '',
					type: file.type || '',
					status: 'success'
				}));
				console.log('displayFileList:', result);
				return result;
			}
		},
		data() {
			return {
				showStartTimePicker: false,
				showEndTimePicker: false,
				showMap: false,
				show: false,
				minDate: '',
				maxDate: '',
				trainerId: '',
				locationData: {},
				isUpdatingFromCache: false,
				ignoreNextCacheUpdate: false,
				isUploading: false, // 跟踪上传状态
				hasUserInteracted: false, // 跟踪用户是否已经交互过
				uploadedImages: [], // 独立跟踪上传的图片
				formData: {
					name: '',
					type: '',
					min_age: '',
					max_age: '',
					min_participants: '',
					max_participants: '',
					start_time: '',
					end_time: '',
					address: '',
					description: '',
				},
				fileList: [],
				showSheet: false,
				calendarShow: false,
				calendarType: '',
				actionSheetList: [{
						text: '冬令营',
						value: 'winter'
					},
					{
						text: '夏令营',
						value: 'summer'
					},
					{
						text: '普通',
						value: 'common'
					},
					{
						text: '公益',
						value: 'welfare'
					}
				],
				uploadUrl: baseURL + '/businessapi/Upload/image',
				uploadHeaders: {
					version: '3.1.0',
					token: store.getters.token,
				},
				defaultDate: '',
				mapUrl: baseURL + '/admin/map',
				errors: {},
				currentStep: 1,
				componentKey: 0,
				tempUploadedFile: null // 临时保存上传的文件，避免立即触发缓存
			};
		},
		methods: {
			chooseStartTime() {
				this.showStartTimePicker = true
			},
			toChooseMap() {
				// #ifdef APP
				this.$Router.push({
					path: `/components/web-view/web-view`,
					query: {
						url: encodeURIComponent(this.mapUrl)
					}
				})
				// #endif
				// #ifdef H5
				this.showMap = true
				// #endif
			},
			openMap() {
				this.$refs.mapSelector.open();
			},
			closeMap() {
				this.showMap = false;
			},
			handlerSelectMap(data) {
				console.log('选择的位置完整数据:', JSON.stringify(data));
				
				// 处理可能的嵌套数据结构（如来自postMessage的数据）
				let locationData = data;
				if (data.data && data.data.type === 'locationSelected' && data.data.location) {
					locationData = data.data.location;
					console.log('从postMessage中提取location数据:', locationData);
				} else if (data.location && typeof data.location === 'object') {
					console.log('直接使用data中的location数据');
				}
				
				// 确保address是字符串
				let addressStr = '';
				if (typeof locationData.address === 'string') {
					addressStr = locationData.address;
				} else if (typeof locationData.address === 'object' && locationData.address) {
					addressStr = locationData.address.name || '';
				}
				
				this.formData.address = addressStr;
				
				// 获取省市区ID并进行有效性检查
				let provinceId = 0;
				let cityId = 0;
				let districtId = 0;
				
				try {
					// 尝试直接转换
					if (locationData.provinceCode) {
						provinceId = Number(locationData.provinceCode) || 0;
					}
					if (locationData.cityCode) {
						cityId = Number(locationData.cityCode) || 0;
					}
					if (locationData.districtCode) {
						districtId = Number(locationData.districtCode) || 0;
					}
					
					// 临时解决方案：如果在长沙，使用固定的ID
					if (locationData.province && locationData.province.includes('湖南') || 
					    locationData.city && locationData.city.includes('长沙')) {
						provinceId = 430000;
						cityId = 430100;
					}
					
					console.log('解析后的省市区ID:', provinceId, cityId, districtId);
				} catch (e) {
					console.error('转换省市区ID失败:', e);
				}
				
				this.formData.province_id = provinceId;
				this.formData.city_id = cityId;
				this.formData.district_id = districtId;
				
				// 提取经纬度 - 尝试从多个可能的位置提取
				let longitude = '';
				let latitude = '';
				
				// 1. 从location对象提取
				if (locationData.location && typeof locationData.location === 'object') {
					if (locationData.location.lng && locationData.location.lat) {
						longitude = locationData.location.lng;
						latitude = locationData.location.lat;
						console.log('从location对象提取经纬度:', {lng: longitude, lat: latitude});
					}
				}
				
				// 2. 从根对象提取
				if (!longitude && !latitude && locationData.lng && locationData.lat) {
					longitude = locationData.lng;
					latitude = locationData.lat;
					console.log('从根对象提取经纬度:', {lng: longitude, lat: latitude});
				}
				
				// 3. 从position.point对象提取
				if (!longitude && !latitude && 
					locationData.position && 
					locationData.position.point) {
					longitude = locationData.position.point.longitude;
					latitude = locationData.position.point.latitude;
					console.log('从position.point对象提取经纬度:', {lng: longitude, lat: latitude});
				}
				
				// 4. 从location.position.point对象提取
				if (!longitude && !latitude && 
					locationData.location && 
					locationData.location.position && 
					locationData.location.position.point) {
					longitude = locationData.location.position.point.longitude;
					latitude = locationData.location.position.point.latitude;
					console.log('从location.position.point对象提取经纬度:', {lng: longitude, lat: latitude});
				}
				
				this.formData.longitude = longitude;
				this.formData.latitude = latitude;
				
				this.$set(this.formData, 'location', addressStr);
				
				console.log('设置后的表单数据:', JSON.stringify({
					address: this.formData.address,
					province_id: this.formData.province_id,
					city_id: this.formData.city_id,
					district_id: this.formData.district_id,
					longitude: this.formData.longitude,
					latitude: this.formData.latitude,
					location: this.formData.location
				}));
				
				this.showMap = false;
			},
			showActionSheet() {
				this.showSheet = true;
			},
			selectType(index) {
				this.formData.type = this.actionSheetList[index].value;
				this.showSheet = false;
			},
			ensureFullUrl(url) {
				try {
					if (!url) return '';
					if (typeof url !== 'string') {
						console.error('URL不是字符串类型:', url);
						return '';
					}
					
					// 处理已经是完整URL的情况
					if (url.startsWith('http')) return url;
					
					// 处理相对路径
					return `https://txjmk-test.oss-cn-shenzhen.aliyuncs.com/${url}`;
				} catch (err) {
					console.error('URL处理错误:', err);
					return '';
				}
			},
			onChooseFile() {
				// 用户选择文件时，标记为已交互，开始上传状态
				this.hasUserInteracted = true;
				this.isUploading = true;
				console.log('用户选择文件，开始上传');
			},
			afterRead(event) {
				try {
					console.log('上传成功事件:', JSON.stringify(event.data));
					
					// 上传完成，重置上传状态
					this.isUploading = false;
					
					if (event.data && event.data.url) {
						const newFile = {
							url: this.ensureFullUrl(event.data.url),
							name: event.data.name || '',
							type: event.data.type || '',
							status: 'success'
						};
						
						console.log('上传成功，URL:', newFile.url);
						
						// 上传成功后，暂时保存到临时变量，不立即触发缓存
						this.tempUploadedFile = newFile;
						
						console.log('上传成功，保存到临时变量，不立即更新缓存');
					}
				} catch (err) {
					console.error('处理上传错误:', err);
					// 上传出错也要重置状态
					this.isUploading = false;
				}
			},
			deletePic(index) {
				console.log('删除图片，索引:', index);
				
				// 标记用户已交互
				this.hasUserInteracted = true;
				
				// 清空临时上传的文件
				this.tempUploadedFile = null;
				
				// 删除时只更新缓存，不立即更新显示数据
				const cacheData = {
					...this.formData,
					uploadedImages: [] // 清空缓存中的图片
				};
				
				console.log('删除图片，清空临时文件和缓存');
				this.$emit('updateCache', cacheData);
			},
			validateForm() {
				this.errors = {}; // 清空之前的错误
				let isValid = true;

				// 活动名称验证
				if (!this.formData.name || this.formData.name.trim() === '') {
					this.errors.name = '请输入活动名称';
					isValid = false;
				} else if (this.formData.name.length < 2) {
					this.errors.name = '活动名称至少2个字符';
					isValid = false;
				} else if (this.formData.name.length > 50) {
					this.errors.name = '活动名称不能超过50个字符';
					isValid = false;
				}

				// 活动类型验证
				if (!this.formData.type) {
					this.errors.type = '请选择活动类型';
					isValid = false;
				}

				// 适用年龄验证
				if (!this.formData.min_age || !this.formData.max_age) {
					this.errors.age = '请填写完整的适用年龄范围';
					isValid = false;
				} else {
					const minAge = parseInt(this.formData.min_age);
					const maxAge = parseInt(this.formData.max_age);
					
					if (isNaN(minAge) || isNaN(maxAge)) {
						this.errors.age = '年龄必须是数字';
						isValid = false;
					} else if (minAge < 0 || maxAge < 0) {
						this.errors.age = '年龄不能为负数';
						isValid = false;
					} else if (minAge > maxAge) {
						this.errors.age = '最小年龄不能大于最大年龄';
						isValid = false;
					} else if (maxAge > 100) {
						this.errors.age = '年龄不能超过100岁';
						isValid = false;
					} else if (minAge < 1) {
						this.errors.age = '最小年龄不能小于1岁';
						isValid = false;
					}
				}

				// 报名人数验证
				if (!this.formData.min_participants || !this.formData.max_participants) {
					this.errors.participants = '请填写完整的报名人数范围';
					isValid = false;
				} else {
					const minPart = parseInt(this.formData.min_participants);
					const maxPart = parseInt(this.formData.max_participants);
					
					if (isNaN(minPart) || isNaN(maxPart)) {
						this.errors.participants = '人数必须是数字';
						isValid = false;
					} else if (minPart < 1 || maxPart < 1) {
						this.errors.participants = '人数不能少于1人';
						isValid = false;
					} else if (minPart > maxPart) {
						this.errors.participants = '最小人数不能大于最大人数';
						isValid = false;
					} else if (maxPart > 1000) {
						this.errors.participants = '人数不能超过1000人';
						isValid = false;
					}
				}

				// 时间验证
				if (!this.formData.start_time) {
					this.errors.start_time = '请选择活动开始时间';
					isValid = false;
				}
				
				if (!this.formData.end_time) {
					this.errors.end_time = '请选择活动结束时间';
					isValid = false;
				}
				
				if (this.formData.start_time && this.formData.end_time) {
					const startTime = new Date(this.formData.start_time);
					const endTime = new Date(this.formData.end_time);
					
					if (startTime >= endTime) {
						this.errors.end_time = '结束时间必须晚于开始时间';
						isValid = false;
					}
					
					// 检查是否是未来时间
					const now = new Date();
					if (startTime <= now) {
						this.errors.start_time = '开始时间必须是未来时间';
						isValid = false;
					}
				}

				// 地址验证
				if (!this.formData.address || this.formData.address.trim() === '') {
					this.errors.address = '请选择活动地点';
					isValid = false;
				}

				// 简介验证
				if (!this.formData.description || this.formData.description.trim() === '') {
					this.errors.description = '请输入活动简介';
					isValid = false;
				} else if (this.formData.description.length < 10) {
					this.errors.description = '活动简介至少10个字符';
					isValid = false;
				} else if (this.formData.description.length > 500) {
					this.errors.description = '活动简介不能超过500个字符';
					isValid = false;
				}

				// 封面图片验证
				console.log('图片验证 - formData.images:', this.imageUrls);
				console.log('图片验证 - 缓存中的图片:', this.formCache?.uploadedImages);
				console.log('图片验证 - 临时上传的文件:', this.tempUploadedFile);
				
				// 检查当前显示的图片、缓存中的图片或临时上传的文件
				const currentImages = this.imageUrls;
				const cachedImages = this.formCache?.uploadedImages || [];
				const tempImage = this.tempUploadedFile ? [this.tempUploadedFile] : [];
				const hasImages = currentImages.length > 0 || cachedImages.length > 0 || tempImage.length > 0;
				
				if (!hasImages) {
					this.errors.images = '请上传至少一张活动封面图片';
					isValid = false;
				} else {
					const totalImages = Math.max(currentImages.length, cachedImages.length, tempImage.length);
					if (totalImages > 5) {
						this.errors.images = '最多只能上传5张图片';
						isValid = false;
					}
				}

				return isValid;
			},

			async save() {
				if (!this.validateForm()) return;
				
				this.isUpdatingFromCache = true;  // 暂时禁用缓存
				try {
					// 获取图片数据：优先使用临时上传的文件，然后是当前显示的，最后是缓存的
					let imageUrls = [];
					
					if (this.tempUploadedFile) {
						// 如果有临时上传的文件，使用它
						imageUrls = [this.tempUploadedFile.url];
						console.log('使用临时上传的文件:', this.tempUploadedFile.url);
					} else if (this.imageUrls.length > 0) {
						// 否则使用当前显示的图片
						imageUrls = this.imageUrls;
						console.log('使用当前显示的图片:', this.imageUrls);
					} else {
						// 最后使用缓存中的图片
						imageUrls = (this.formCache?.uploadedImages || []).map(file => file.url);
						console.log('使用缓存中的图片:', imageUrls);
					}
					
					const submitData = {
						...this.formData,
						images: imageUrls
					};
					
					console.log('提交的图片数据:', imageUrls);
					
					// 提交成功后，将临时文件保存到缓存
					if (this.tempUploadedFile) {
						const cacheData = {
							...this.formData,
							uploadedImages: [this.tempUploadedFile]
						};
						this.$emit('updateCache', cacheData);
						this.tempUploadedFile = null; // 清空临时文件
						console.log('提交成功，将临时文件保存到缓存');
					}
					
					if (this.activityId) {
						await editActivity({
							id: this.activityId,
							...submitData
						});
						// 更新活动数据
						this.$emit('updateData', submitData);
						// 编辑活动时触发next事件
						this.$emit('next');
					} else {
						const res = await addActivity(submitData);
						this.$emit('created', res.id); // 通知父组件新创建的ID
						// 更新活动数据
						this.$emit('updateData', { ...submitData, id: res.id });
						// 新建活动时不触发next事件，因为created事件已经会处理跳转
					}
				} catch (error) {
					console.error('保存活动失败:', error);
					uni.showToast({
						title: '保存失败，请重试',
						icon: 'none',
						duration: 2000
					});
				} finally {
					this.$nextTick(() => {
						this.isUpdatingFromCache = false;  // 恢复缓存功能
					});
				}
			},

			async trainerList() {
				try {
					const res = await trainerList();
					console.log('trainerList', res.list.data)
					if (res && res.list && res.list.data && res.list.data.length > 0) {
						this.trainerId = res.list.data[0].id;
						console.log('获取到的训练师 id:', this.trainerId);
					} else {
						console.log('未找到有效的训练师数据');
					}
				} catch (error) {
					console.error('获取训练师列表失败:', error);
				}
			},
			handleStartTimeConfirm(e) {
				this.formData.start_time = formatDate(e);
				this.formData.start_time_text = this.formData.start_time
				this.showStartTimePicker = false;
			},
			handleEndTimeConfirm(e) {
				this.formData.end_time = formatDate(e);
				this.formData.end_time_text = this.formData.end_time
				this.showEndTimePicker = false;
			},
			clearError(field) {
				if (this.errors[field]) {
					this.errors[field] = '';
				}
			},
			saveToCache: debounce(function() {
				// 如果当前正在从缓存更新，则不触发保存
				if (this.isUpdatingFromCache || this.ignoreNextCacheUpdate) {
					console.log('跳过缓存保存 - 当前正在更新或已忽略');
					return;
				}
				
				// 设置忽略标志，防止下一次watch fileList触发
				this.ignoreNextCacheUpdate = true;
				
				console.log('保存到缓存，uploadedImages长度:', this.uploadedImages.length);
				console.log('保存到缓存，imageUrls:', this.imageUrls);
				const cacheData = {
					...this.formData,
					uploadedImages: this.uploadedImages.map(file => ({
						url: file.url,
						name: file.name,
						type: file.type,
						status: file.status
					}))
				};
				this.$emit('updateCache', cacheData);
				
				// 200ms后重置忽略标志
				setTimeout(() => {
					this.ignoreNextCacheUpdate = false;
				}, 200);
			}, 500),
			loadFromCache() {
				try {
					// 已经在更新中，直接返回
					if (this.isUpdatingFromCache) {
						console.log('已在更新缓存中，跳过本次加载');
						return;
					}
					
					this.isUpdatingFromCache = true;
					console.log('开始从缓存加载');
					console.log('缓存前uploadedImages长度:', this.uploadedImages.length);
					console.log('formCache.uploadedImages:', JSON.stringify(this.formCache?.uploadedImages || []));
					
					// 重置为空，确保没有旧数据
					this.uploadedImages = [];
					
					// 只加载一张有效图片
					if (this.formCache?.uploadedImages && this.formCache.uploadedImages.length > 0) {
						// 只取最后一个有效文件（最新上传的）
						for (let i = this.formCache.uploadedImages.length - 1; i >= 0; i--) {
							const file = this.formCache.uploadedImages[i];
							if (file && file.url) {
								this.uploadedImages = [{
									url: this.ensureFullUrl(file.url),
									name: file.name || '',
									type: file.type || '',
									status: 'success'
								}];
								console.log('找到有效缓存文件，索引:', i);
								break; // 只取一个后立即退出
							}
						}
						
						// 如果从缓存加载了图片，重置用户交互状态，允许显示
						if (this.uploadedImages.length > 0) {
							this.hasUserInteracted = false;
							console.log('从缓存加载图片，重置用户交互状态');
						}
					}
					console.log('从缓存加载后的uploadedImages长度:', this.uploadedImages.length);
					console.log('从缓存加载后的uploadedImages:', JSON.stringify(this.uploadedImages));
					
					// 使用延时确保标志位清除
					setTimeout(() => {
						this.isUpdatingFromCache = false;
						console.log('缓存加载完成，重置状态');
					}, 200);
				} catch (err) {
					console.error('加载缓存错误:', err);
					this.uploadedImages = [];
					this.isUpdatingFromCache = false;
				}
			},
			goToStepOne() {
				this.currentStep = 1;
				this.componentKey += 1; // 强制重新渲染
			},
		},

		watch: {
			locationData: {
				handler(newVal) {
					if (newVal && newVal.address) {
						this.formData.location = newVal.address;
					}
				},
				deep: true,
				immediate: true
			},
			activityData: {
				handler(newVal) {
					// 如果正在从缓存更新，则不处理
					if (this.isUpdatingFromCache) {
						return;
					}
					
					// 简化处理逻辑
					if (!newVal || typeof newVal !== 'object') {
						return;
					}
					
					// 设置标志位，防止触发formData的watch
					this.isUpdatingFromCache = true;
					
					let keys = ['name', 'max_age', 'min_age', 'max_participants', 'min_participants', 'start_time',
						'start_time_text', 'end_time', 'end_time_text', 'address', 'description', 'type'
					];
					
					let hasChanges = false;
					
					for (const key of keys) {
						if (newVal[key] !== undefined && newVal[key] !== this.formData[key]) {
							this.formData[key] = newVal[key];
							hasChanges = true;
						}
					}
					
					// 重置标志位
					this.isUpdatingFromCache = false;
					
					console.log('activityData更新完成，images长度:', this.imageUrls.length);
				},
				deep: true,
				immediate: true
			},
			formCache: {
				handler(newVal) {
					if (this.isUpdatingFromCache || this.ignoreNextCacheUpdate) {
						console.log('跳过formCache处理 - 当前正在更新');
						return;
					}
					
					console.log('formCache变化，准备加载');
					this.loadFromCache();
				},
				deep: true,
				immediate: true
			},
			fileList: {
				handler() {
					// 如果正在从缓存更新或忽略下一次更新，不触发保存
					if (!this.isUpdatingFromCache && !this.ignoreNextCacheUpdate) {
						this.saveToCache();
					}
				},
				deep: true
			}
		},

		mounted() {
			this.trainerList();
			this.locationData = uni.getStorageSync('locationData');
			// 初始化时也设置一次地址
			if (this.locationData && this.locationData.address) {
				this.formData.location = this.locationData.address;
			}
			uni.$on('locationConfirm', obj => {
				console.log('addressObj', obj)
				this.handlerSelectMap(obj)
			});
			
			// 确保初始状态是空的
			this.fileList = [];
			
			// 重置用户交互状态和临时文件
			this.hasUserInteracted = false;
			this.isUploading = false;
			this.tempUploadedFile = null;
			
			// 从缓存加载（如果有）
			this.$nextTick(() => {
				this.loadFromCache();
			});
		}
	};
</script>

<style lang="scss">
	/* 添加一个不带 scoped 的全局样式块 */
	.u-action-sheet-item__subtext.data-v-5a210273,
	.u-action-sheet-item__subtext.u-line-1.data-v-5a210273 {
		margin-top: 0 !important;
		padding-top: 20rpx !important;
	}
</style>

<style lang="scss" scoped>
	.step-item {
		background-color: #ffffff;
		border-radius: 8rpx;
		padding: 20rpx;
	}

	/* 步骤头部样式 */
	.step-header {
		text-align: center;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #d5d5d5;
	}

	.step-icon {
		font-size: 48rpx;
		margin-bottom: 12rpx;
	}

	.step-title-main {
		font-size: 32rpx;
		font-weight: 500;
		color: #000000;
		margin-bottom: 8rpx;
	}

	.step-description {
		font-size: 24rpx;
		color: #666;
		line-height: 1.4;
	}

	.form-container {
		padding: 20rpx;
	}

	.form-item {
		margin-bottom: 30rpx;

		.label {
			font-size: 28rpx;
			color: #000000;
			font-weight: 500;
			margin-bottom: 10rpx;
		}

		/deep/ .u-input {
			margin-top: 8rpx;
		}

		.description-wrapper {
			height: 200rpx;
			background: #ffffff;
			border-radius: 8rpx;
			border: 1rpx solid #dcdfe6;
			padding: 20rpx;
		}
	}

	.age-range,
	.number-range,
	.duration {
		display: flex;
		align-items: center;

		.separator {
			padding: 0 20rpx;
			font-size: 24rpx;
			color: #666;
		}

		/deep/ .u-input {
			flex: 1;

			&__content {
				padding: 10rpx;
				background-color: #ffffff;
				border: 1px solid #dcdfe6;
				border-radius: 4px;
			}
		}
	}

	.bottom-buttons {
		display: flex;
		justify-content: center;
		padding: 40rpx 20rpx;

		.next-btn {
			width: 331rpx;
			height: 90rpx;
			background: #0dc160;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			text {
				font-size: 32rpx;
				color: #ffffff;
			}
		}
	}

	.cell-wrapper {
		/deep/ .u-cell {
			padding: 0;

			&-group {
				margin: 0;
			}

			&-item {
				padding-left: 0;

				&__body {
					padding: 10rpx 0;
				}
			}
		}
	}

	.input-with-icon {
		position: relative;

		.suffix-icon {
			position: absolute;
			right: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			z-index: 1;
		}

		/deep/ .u-input {
			&__input {
				padding-right: 60rpx;
			}
		}
	}

	.inputview {
		border-radius: 4px;
		border: 1px solid #dcdfe6;
		font-size: 28rpx;
		min-height: 36px;
		padding: 0px 10px;
		margin-top: 4px;
		text-align: left;
		color: rgb(192, 196, 204);
		display: flex;
		align-items: center;
	}

	/* 错误信息样式 */
	.error-text {
		font-size: 24rpx;
		color: #ff4757;
		margin-top: 8rpx;
		line-height: 1.4;
	}

	.quick-navigation {
		display: flex;
		justify-content: space-between;
		padding: 20rpx;

		.quick-nav-btn {
			width: 48%;
			height: 80rpx;
			background: #0dc160;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			text {
				font-size: 32rpx;
				color: #ffffff;
			}
		}
	}
</style>